package cn.bdqn.auth_provider.service;

import cn.bdqn.common.*;
import cn.bdqn.pojo.Users;
import cn.bdqn.service.TokenService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 2018/9/21
 * token业务类
 */
@Component
@Service(interfaceClass = TokenService.class)
public class TokenServiceImpl implements TokenService {

//常量 token：

    private final String TOKEN_PRIXE = "token:";

    @Resource
    private VerificationToken verificationToken;
    @Resource
    private RedisUtils redisUtils;

    /**
     * token:加密的密码-手机-时间
     *
     * @param users
     * @return
     */
    @Override
    public String getToken(Users users) {

        StringBuilder sb = new StringBuilder(TOKEN_PRIXE);
        sb.append(MD5Utils.getMD5(users.getPassword(), 32));

        sb.append("-" + users.getPhone());

        sb.append("-" + new SimpleDateFormat(Constants.TOKEN_DATE_FORMAT).format(new Date()));

        String token = sb.toString();

        redisUtils.set(token, Constants.TOKEN_VALID_TIME, JSON.toJSONString(users));

        return token;

    }

    /**
     * 置换token
     *
     * @param token
     * @return
     * @throws Exception
     */
    @Override
    public String replacementToken(String token) throws Exception {
        //验证token
        Users users = verificationToken.tokenVerify(token);
        if (null == users) {
            throw new Exception("token无效，请重新登录！");
        }
        //判断时间是否符合置换条件
        String[] to = token.split("-");

        Date createDate = DateUtils.stringToDate(Constants.TOKEN_DATE_FORMAT, to[2]);

        //long passed = new Date().getTime() - createDate.getTime();

        long passed = System.currentTimeMillis() - createDate.getTime();

        if (passed < Constants.TOKEN_REPLACEMENT_TIME) {
            throw new Exception("token无需置换！");
        }
        //生成新token
        String newToken = getToken(users);
        //设置新token
        redisUtils.set(newToken, Constants.TOKEN_VALID_TIME, JSON.toJSONString(users));
        //设置旧token
        redisUtils.set(token, Constants.TOKEN_REMAIN_TIME, JSON.toJSONString(users));
        return newToken;

    }

    @Override
    public Boolean logOut(String token) throws Exception {
        if (token == null || token.equals("")) {
            throw new Exception("参数错误");
        }
        if (redisUtils.exist(token)) {
            redisUtils.delete(token);
        } else {
            throw new Exception("token不存在！");
        }
        return true;
    }
}



